#!/usr/bin/env pythonw
"""show_object.py FILE

Display a model from an obj file"""

import sys
from eos import obj
import ctypes
import pyglet
from pyglet.gl import *

assert len(sys.argv) > 1, 'No obj file specified\n%s' % __doc__

win = pyglet.window.Window(resizable=True, visible=False,
	config=Config(sample_buffers=1, samples=4, depth_size=24, double_buffer=True))
win.clear()

def on_resize(width, height):
	"""Initial settings for the OpenGL state machine, clear color, window size, etc"""
	glViewport(0, 0, width, height)
	glMatrixMode(GL_PROJECTION)
	glLoadIdentity()
	gluPerspective(70, 1.0*width/height, 0.1, 1000.0)
	glMatrixMode(GL_MODELVIEW)
	glLoadIdentity()
	glEnable(GL_BLEND)
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
	glShadeModel(GL_SMOOTH)
	fourfv = ctypes.c_float * 4
	glEnable(GL_COLOR_MATERIAL)
	glEnable(GL_DEPTH_TEST)
	glEnable(GL_CULL_FACE)
	glDepthFunc(GL_LEQUAL)
	glEnable(GL_LIGHTING)
	glEnable(GL_LIGHT0)
	glLightfv(GL_LIGHT0, GL_POSITION, fourfv(-1, 1, 1, 0))
	glLightfv(GL_LIGHT0, GL_AMBIENT, fourfv(.1, .1, .1, 3))
	glLightfv(GL_LIGHT0, GL_DIFFUSE, fourfv(.4, .4, .4, 1))
	glLightfv(GL_LIGHT0, GL_SPECULAR, fourfv(1, 1, 1, 1))
	glEnable(GL_POLYGON_OFFSET_FILL)
	glPolygonOffset(1., 1.)

win.on_resize = on_resize

model = obj.Model(sys.argv[1])

rot = 0
rotspeed = 30

def update(dt):
	global rot
	rot += rotspeed * dt

pyglet.clock.schedule_interval(update, 1.0/30)

@win.event
def on_draw():
	win.clear()
	glLoadIdentity()
	glTranslatef(0,0,-10)
	glRotatef(50, 1, 0, 0)
	glRotatef(rot, 0, 1, 0)
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
	glEnable(GL_LIGHTING)
	glEnable(GL_CULL_FACE)
	glEnable(GL_DEPTH_TEST)
	glColor3f(.3, .5, .3)
	model.draw()
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
	glDisable(GL_LIGHTING)
	glDisable(GL_CULL_FACE)
	glLineWidth(1)
	glColor4f(0  ,1, .5, 1.0)
	model.draw()
	glLineWidth(3)
	glColor4f(0  ,1, .5, 0.15)
	model.draw()
	glLineWidth(5)
	glColor4f(0  ,1, .5, 0.07)
	model.draw()
	glDisable(GL_DEPTH_TEST)
	glLineWidth(2)
	model.draw()


win.set_visible(True)
pyglet.app.run()
